https://leetcode.com/problems/next-permutation/
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3→1,3,23,2,1→1,2,31,1,5→1,5,1
The test case given in the question is not enough for us to understand this question. So I will use another example to explain this question.
Let 1,2,3,4,5 is the input array nums. It is easy to write down its next permutation which is 1,2,3,5,4. What about 1,2,3,5,4‘s next permutation? It’s 1,2,4,3,5. And why?
The reason is that we have listed all possible permutations that index[nums.length - 2] greater than index[nums.length - 1], we should think about condition that the last three numbers contain a non-lexicographically permutation of numbers. The smallest one is that index[nums.length - 3] is the second smallest number in the last three numbers, and numbers after that should be in an ascending order. Why numbers should be in an ascending order? Because the question defines that this is a smallest condition.
The following should be 1,2,4,5,3, 1,2,5,3,4, 1,2,5,4,3, 1,3,2,4,5, 1,3,2,5,4, 1,3,4,2,5, 1,3,4,5,2, 1,3,5,2,4, 1,3,5,4,2, 1,4,2,3,5, 1,4,2,5,3, 1,4,3,2,5, 1,4,3,5,2, 1,4,5,2,3, 1,4,5,3,2, etc.
1 |
|
Another version of solution which helps me a lot to understand this question.
https://leetcode.com/discuss/85045/20-line-1ms-in-place-java-code-with-expalantion
- scan from right to left, find first pair where a[i] > a[i-1]. note that a[i:] is non-ascending.
- scan from right to left again, find first element a[j] where a[j] > a[i-1]. since a[i:] is non-ascending, a[j] is the smallest number that > a[i-1].
- swap a[i-1] with a[j]. note that after swap, a[i:] remains non-ascending.
- reverse a[i:] so that a[i:] becomes non-descending.
1 |
|